package top.gohigh.springboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.gohigh.springboot.model.User;
import top.gohigh.springboot.model.UserGroup;
import top.gohigh.springboot.service.UserGroupService;
import top.gohigh.springboot.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    UserService userService;

    @Autowired
    UserGroupService userGroupService;


    @GetMapping("/addGroup/{name}")
    public UserGroup addGroup(@PathVariable String name){
        return userGroupService.addGroup(name);
    }


    @GetMapping("/addRole/{uid}/{rid}")
    public User addRole(@PathVariable Long uid,@PathVariable Long rid){
        return userService.addRole(uid,rid);
    }

    @GetMapping("/login/{username}/{pwd}")
    public String login(@PathVariable String username,@PathVariable String pwd){
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken token= new UsernamePasswordToken(username,pwd);
        try{
            subject.login(token);
            return "login succ";
        }catch (UnknownAccountException e){
            return "no acc";
        }catch (IncorrectCredentialsException e){
            return "pwd err";
        }


    }

    @GetMapping("/register/{username}/{pwd}/{groupId}")
    public String register(@PathVariable String username,@PathVariable String pwd,@PathVariable Long groupId){

        userService.add(username,pwd,groupId);
        return "succ";
    }


    @GetMapping("/update")
    @RequiresPermissions("user:update")
    public String update(){
        return "update";
    }


    @GetMapping("/del")
    @RequiresPermissions("user:del")
    public String del(){
        return "del";
    }

    @GetMapping("/add")
    @RequiresPermissions("user:add")
    public String add(){
        return "add";
    }

    @GetMapping("/test")
    public String test(){
        return "test";
    }


}
